package com.taotao.async.task.spring.handler;

import com.taotao.async.task.Task;
import com.taotao.async.task.TaskHub;
import com.taotao.async.task.spring.excption.SpringTaskException;
import com.taotao.async.task.utils.MessageFormatUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class TaskHandlerBeanRegister implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        TaskHandler th = bean.getClass().getAnnotation(TaskHandler.class);
        if (null == th) {
            return bean;
        }

        if (!(bean instanceof Task)) {
            throw new SpringTaskException(SpringTaskException.CODE0 + 1, "TaskHandler bean must implements com.taotao.async.task.Task!");
        }

        Task t = TaskHub.getTask(th.code());
        if (null != t) {
            throw new SpringTaskException(SpringTaskException.CODE0 + 2, MessageFormatUtil.format("duplex taskcode for {},one is {}, other is  {}!", th.code(), t.getClass(), bean.getClass()));
        }
        TaskHub.addTask(th.code(), (Task) bean);

        return bean;
    }

}
